/**
 * Created by yqr on 2023/08/07.
 */
import config from './config';
import axios from 'axios'
import qs from 'qs'
import myMixin from '../common/myMixin.js';
import {road} from '../road.js'
import Vue from 'vue'
import routerIndex from '../router/index'
import store from '../vuex/store.js'
// import {
//   Message,
// } from "element-ui";

//阻止重复请求 start 1
function getRequestKey(config) {
  let {
    method,
    url,
    params,
    data
  } = config;
  // axios中取消请求及阻止重复请求的方法
  // 参数相同时阻止重复请求：
  return [method, url, JSON.stringify(params), JSON.stringify(data)].join("&");
  // 请求方法相同，参数不同时阻止重复请求
  // return [method, url].join("&");
}

let pendingRequest = new Map();

function addPendingRequest(config) {
  // console.log(config.url)
  let requestKey = getRequestKey(config);
  config.cancelToken = config.cancelToken || new axios.CancelToken((cancel) => {
    if (!pendingRequest.has(requestKey)) {
      pendingRequest.set(requestKey, cancel);
    }
  });
}
//阻止重复请求 end 1


function removePendingRequest(config) {
  let requestKey = getRequestKey(config);
  if (pendingRequest.has(requestKey)) {
    // 如果是重复的请求，则执行对应的cancel函数
    let cancel = pendingRequest.get(requestKey);
    cancel(requestKey);
    // 将前一次重复的请求移除
    pendingRequest.delete(requestKey);
  }
}


axios.defaults.withCredentials = false;
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// post请求后台无法获取传递参数
// qs.stringify配置'application/x-www-form-urlencoded'请求头
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';//配置请求头
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';//配置请求头
axios.defaults.headers.post['apptype'] = 'admin';//配置请求头apptype为admin
axios.defaults.transformRequest = function (data) {
  // return qs.stringify(data, {arrayFormat: 'brackets'})
  return JSON.stringify(data)
}

//添加一个请求拦截器
axios.interceptors.request.use(function (config) {
  // console.dir(config);

  //传参去除空格
  if(myMixin&&myMixin.methods.isEmptyNew()&&config&&config.data){
    if(!myMixin.methods.isEmptyNew(config.data)){
      //Object.entries(): 返回一个对象自身的（不含继承的）所有可遍历（enumerable）属性的键值对的数组
      let arr = Object.entries(config.data)
      arr.forEach((item,index )=>{
        if(myMixin.methods.emptyString(item[1])){
          //替换空格
          // item[1] = item[1].replace(/\s*/g, "")
          //替换空格
          item[1] = item[1].replace(/^\s+|\s+$/g, "")
        }
      })
      //Object.fromEntries(): 将一个键值对数组转为对象
      config.data = {...Object.fromEntries(arr)}
    }
  }

  //阻止重复请求 start 2
  // 检查是否存在重复请求，若存在则取消已发的请求
  removePendingRequest(config);
  // 把当前请求信息添加到pendingRequest对象中
  addPendingRequest(config);
  //阻止重复请求 end 2

  return config;
}, function (error) {
  // Do something with request error
  return Promise.reject(error);
});

// 添加一个响应拦截器
let loginReturn = false;
axios.interceptors.response.use(function (response) {
  //阻止重复请求 start 3
  // 对响应数据做点什么
  removePendingRequest(response.config);
  //阻止重复请求 end 3

  const { code } = response.data;
  if (code == 1001) {
    //未登录
    if(loginReturn) return response.data;
    loginReturn = true;
    // window.localStorage.removeItem('randToken');
    store.commit('clearMember')
    //未登录
    road.$message.error("登录已过期,请重新登录");
    if(myMixin&&myMixin.methods.openFullScreen()){
      myMixin.methods.closeFullScreen(myMixin.methods.openFullScreen());
    }


    Vue.nextTick(function () {
      // DOM 现在更新了
      // `this` 绑定到当前实例
      routerIndex.push('/login');
    })
  }else{
    if(myMixin&&myMixin.methods.sleep()){
      myMixin.methods.sleep(5000).then(()=>{
        loginReturn = false;
      })
    }
  }

  // console.dir(response);
  return response.data;
  // return response;
}, function (error) {
  // Do something with response error

  //阻止重复请求 start 4
  // 从pendingRequest对象中移除请求
  removePendingRequest(error.config || {});
  if (axios.isCancel(error)) {
    console.log("被取消的重复请求isCancel：" + error.message);
    return Promise.reject({isCancel:true});
  }else{
    return Promise.reject(error);
  }
  // //阻止重复请求 end 4
  // return Promise.reject(error);
});

//基本地址
let base = config.isDev ? ''  : config.baseUrl;
let crmUrl = config.isDev ? ''  : config.crmUrl;
// console.log("base",base)

//测试使用
export const ISDEV = config.isDev;
let randToken = null;

//通用方法
export const POST = (url, params) => {
  randToken = localStorage.getItem('randToken')
  // console.log("randToken",randToken)
  if(randToken){
    params.token = randToken
  }

  // console.log("url",url)
  return new Promise((resolve,reject)=>{
    // post请求后台无法获取传递参数urlstringify(params)
    axios.post(`${base}${url}`, params).then(res => {
      // console.log("POST",res.data)
      let obj = res&&res.data ? res.data : {};
      // 实施刷新randToken
      if (obj && obj.token) {
        randToken = obj.token;
        // console.log("randToken",randToken)
        localStorage.setItem('randToken', randToken);
      }
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}

export const GET = (url, params={}) => {
  randToken = localStorage.getItem('randToken')
  // console.log("randToken",randToken)
  if(randToken){
    params.token = randToken
  }
  return new Promise((resolve,reject)=>{
    return axios.get(`${base}${url}`, {params: params}).then(res => {
      let obj = res&&res.data ? res.data : {};
       // 实施刷新randToken
      if (obj && obj.token) {
        randToken = obj.token;
        localStorage.setItem('randToken', randToken);
        // console.log("randToken",randToken)
      }

      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}

export const POSTCRM = (url, params) => {
  // randToken = localStorage.getItem('randToken')
  // // console.log("randToken",randToken)
  // if(randToken){
  //   params.token = randToken
  // }

  // console.log("url",url)
  return new Promise((resolve,reject)=>{
    // post请求后台无法获取传递参数urlstringify(params) => qs.stringify(params)
    axios.post(`${crmUrl}${url}`, params).then(res => {
      // console.log("POST",res.data)
      // let obj = res&&res.data ? res.data : {};
      // // 实施刷新randToken
      // if (obj && obj.token) {
      //   randToken = obj.token;
      //   // console.log("randToken",randToken)
      //   localStorage.setItem('randToken', randToken);
      // }
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}

export const GETCRM = (url, params={}) => {
  // randToken = localStorage.getItem('randToken')
  // // console.log("randToken",randToken)
  // if(randToken){
  //   params.token = randToken
  // }
  return new Promise((resolve,reject)=>{
    return axios.get(`${crmUrl}${url}`, {params: params}).then(res => {
      // let obj = res&&res.data ? res.data : {};
      //  // 实施刷新randToken
      // if (obj && obj.token) {
      //   randToken = obj.token;
      //   localStorage.setItem('randToken', randToken);
      //   // console.log("randToken",randToken)
      // }

      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}

//转义方法
function urlstringify(obj) {//字符串序列化
    var str = '';
    for (let key in obj) {
        if (Object.prototype.toString.call(obj[key]) === '[object Array]' || obj[key].constructor === Object) {
            //数组,对象
            for (var arrKey in obj[key]) {
                if (Object.prototype.toString.call(obj[key][arrKey]) === '[object Array]' || obj[key][arrKey].constructor === Object) {
                    //数组,对象
                    for (var arrarrKey in obj[key][arrKey]) {
                        str += '&' + key + '[' + arrKey + '][' + arrarrKey + ']=' + obj[key][arrKey][arrarrKey];
                    }
                } else {
                    //普通
                    str += '&' + key + '[' + arrKey + ']=' + obj[key][arrKey];
                }
            }
        } else {
            //普通
            str += '&' + key + '=' + obj[key];
        }
    }
    return str.substring(1);
}

